__author__ = 'l4537'
#coding:utf-8
import telnetlib,time,re,sys,pexpect,getpass
#进度条
def view_bar(num,total):
    ret = num / total
    ag = int(ret * 100)
    ab = "\r [%-100s]%d%%" %( '='*num,ag, )
    sys.stdout.write(ab)
    sys.stdout.flush()
def Telnet(ip,user,password,commands):
    try:
        tn = telnetlib.Telnet(ip)
    except Exception as e:
        print("IP 地址连接错误")
        Errlog(ip,e,"地址连接错误,无法连接")
        Startsan()
    tn.read_until(b"login:",timeout=5)
    tn.write(user.encode('ascii') + b"\n")
    if password:
        tn.read_until(b"Password: ",timeout=5)
        tn.write(password.encode('ascii') + b"\n")
    tn.read_some()
    result = tn.read_some()
    rex = r'incorrect'
    tmp = re.search(rex,str(result))
    if not tmp == None:
        print("密码错误")
        Errlog(ip,"账户或者密码错误")
        Startsan()
    for k in range(6):
        tn.write(b"\n")
        time.sleep(1)
    b = 0
    for i in commands:
        comm = i + "\n"
        b +=1
        time.sleep(0.5)
        view_bar(b,len(commands))
        tn.write(str.encode(comm))
    for k in range(20):
        tn.write(b"\n")
    tn.write(b"exit\n")
    data = tn.read_all().decode('utf-8')
    #print (data)
    Log(ip,data)
def Log(ip,data):
    name = str(ip +'-'+ time.strftime('%Y%m%d%H%M') + '.txt')
    file_name = open(name,mode='a')
    file_name.write(data)
    file_name.close()
def Errlog(ip,errmessages):
    time_log = time.strftime('%Y-%m-%d %H:%M:%S')
    err_log = open('messages.log',mode='a')
    err_log.write(time_log + '   '+ ip +"   "+ errmessages + "\n")
    err_log.close()
#传送ip，账号，密码，命令列表，login_s(登入符号)，run_s（每个命令运行结束符号）
def ssh_conn(ip,root,password,command,login_s,run_s):
    try:
        cmd = "ssh "+root +"@"+ip
        child = pexpect.spawn(cmd)
        ret = child.expect([pexpect.TIMEOUT,login_s],timeout=5)
        if ret == 0:
            print("连接错误,请核实IP是否正确")
            Errlog(ip,"连接错误,请核实IP是否正确")
            return None
        child.sendline(password)
        child.expect(run_s)
        data = ""
        for i in command:
            child.sendline(i)
            child.expect(run_s)
            data += bytes.decode(child.before) + "\n"
        Log(ip,data)
        print(data)
        child.close()
    except Exception as e:
        print("连接失败,请确认账号或者密码")
        Errlog(ip,"连接失败,请确认账号或者密码")
if __name__ == "__main__":
    try:
        while True:
            print("1：光交日志收集\n2：富士通存储日志收集\n3:华为存储日志收集\n4:退出\n5:测试192.168.20.60")
            num = int(input("请选择:"))
            if num == 1:
                command = ["slotshow","chassisshow","switchshow","zoneshow","hashow","porterrshow","fanshow","firmwareshow",'version','licenseshow ','uptime','date','fabricshow','memshow',"psshow"]
                ip = str(input("请输入IP地址:"))
                Telnet(ip,"admin","Jxyd@Bc0791san",command)
            elif num == 2:
                ip = str(input("请输入IP地址:"))
                command = ["show disk-error","show disks","show fc-parameters","show hardware-information","show host-affinity","show host-groups","show host-path-state","show host-port-mode","show host-response","show host-wwn-names","show fru-ce"," show led","show lun-groups","show mapping","show raid-groups","show status","show volume-mapping","show volumes","show performance","show port-groups","show port-error"]
                Telnet(ip,"root","Jxydstorage0791",command)
            elif num == 3:
                pass
            elif num ==4:
                sys.exit()
            elif num ==5:
                ip = input("请输入IP地址：")
                root = "root"
                password = "root"
                cmd = ["df -h","uptime","switchshow","zoneshow"]
                login_s = "password:"
                run_s = "[#]"
                ssh_conn(ip,root,password,cmd,login_s,run_s)
    except Exception as e:
        print("程序退出")